//
//  ViewController.swift
//  ZJImagePicker
//
//  Created by micheal on 2018/4/4.
//  Copyright © 2018年 covermedia. All rights reserved.
//

import UIKit
import Photos

class ViewController: UIViewController {

    // 存放系统相册
    var assetArray = [Any]()
    private lazy var tableView:UITableView = {
        
        let table = UITableView.init(frame: self.view.frame, style: UITableViewStyle.plain)
        table.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        table.tableFooterView = UIView()
        table.dataSource = self
        table.delegate = self
        return table
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        // 设置UI
        setupUI()
        
        // 申请权限
        PHPhotoLibrary.requestAuthorization { (status) in
            if status != .authorized {
                return
            }
        }
        assetArray = photoCollection(with: PHAssetCollectionType.smartAlbum)
        print("")
//        PHImageManager.default().requestImage(for: <#T##PHAsset#>, targetSize: <#T##CGSize#>, contentMode: <#T##PHImageContentMode#>, options: <#T##PHImageRequestOptions?#>, resultHandler: <#T##(UIImage?, [AnyHashable : Any]?) -> Void#>)
        
    }
    
    func setupUI() {
        
        self.title = "ZJImagePicker"
        view.addSubview(self.tableView)
    }
    
    /// 根据相册类型获取相册数组
    ///
    /// - Parameter type: 相册类型
    /// - Returns: 指定类型下的所有相册数组
    func photoCollection(with type:PHAssetCollectionType) -> [[String:Any]] {
        
        var photoColletionArray = [[String:Any]]()
        var assetDic = [String:Any]()
        var assetArry = [Any]()
        
        // 获取系统默认有的相册
        /**
         1. album         用户使用应用时自己创建的相册
         2. moment        回忆中的相册
         3. smartAlbum    系统自带的相册
         */
        let systemAssets = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.smartAlbum, subtype: PHAssetCollectionSubtype.albumRegular, options: PHFetchOptions())
        systemAssets.enumerateObjects { (collection, index, stop) in
            
            assetArry.removeAll()
            assetDic.removeAll()
            // 取出当前相册的照片
            let assetFetchResult = PHAsset.fetchAssets(in: collection, options: PHFetchOptions())
            if assetFetchResult.count > 0 {
                
                guard let title = titleTransToChinese(with: collection.localizedTitle) else {return}
                print(title)
                // 取出相册中的照片
                assetFetchResult.enumerateObjects({ (asset, index, stop) in
                    assetArry.append(asset)
                })
                assetDic[title] = assetArry
                photoColletionArray.append(assetDic)
            }
        }
        return photoColletionArray
        
    }
}

func titleTransToChinese(with title:String?) -> String? {
    
    switch title {
        
    case "Recently Added":
        return "最近添加"
    case "Camera Roll":
        return "相机胶卷"
    case "Panoramas":
        return "连拍快照"
    case "Bursts":
        return "全景照片"
    case "Recently Deleted":
        return "最近删除"
    case "Videos":
        return "视频"
    case "Screenshots":
        return "屏幕快照"
    case "Selfies":
        return "自拍"
    case "Animated":
        return "动图"
    default:
        return nil
    }
}

extension ViewController: UITableViewDataSource, UITableViewDelegate {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return assetArray.count
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath
        )
        let dic = assetArray[indexPath.row] as! NSDictionary
        if let title = dic.allKeys.first {

            // 标题
            let assetTitle = title as! String
            let valueArray = dic[assetTitle] as! NSArray
            cell.textLabel?.text = assetTitle + " （\(valueArray.count)）"

        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        tableView.deselectRow(at: indexPath, animated: true)
        let data = assetArray[indexPath.row] as! NSDictionary
        let dataArray = data.allValues.first as! NSArray
        
        let picker = ZJPickerViewController()
        picker.assetArray = dataArray as! [ZJPHAsset]
        self.navigationController?.pushViewController(picker, animated: true)
        
        print(dataArray.count)
        
    }
}
